package com.shuhua.taskServer.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuhua.pojo.entity.TaskCollect;
import com.shuhua.taskServer.service.TaskCollectService;
import com.shuhua.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/taskCollect")
public class TaskCollectController {

    @Autowired
    private TaskCollectService taskCollectService;

    private static final String[] TASKCOLLECT_FIELDS = {"task_id", "craftsman_id", "collect_time"};
    private static final String[] TASK_FIELDS = {"task_id", "title", "task_type", "description", "address", "start_time", "end_time", "budget", "dispatch_mode", "priority_level", "status", "created_at", "updated_at", "remark"};
    private static final String[] CRAFTSMAN_FIELDS = {"craftsman_username", "craftsman_phone", "craftsman_real_name", "craftsman_department", "craftsman_station", "craftsman_avatar"};

    private Map<String, Object> wrapTaskCollect(Map<String, Object> map) {
        if (map == null) return null;
        java.util.LinkedHashMap<String, Object> result = new java.util.LinkedHashMap<>();
        java.util.LinkedHashMap<String, Object> task = new java.util.LinkedHashMap<>();
        java.util.LinkedHashMap<String, Object> craftsman = new java.util.LinkedHashMap<>();
        // 主表字段
        for (String field : TASKCOLLECT_FIELDS) {
            if (map.containsKey(field)) result.put(field, map.get(field));
        }
        // 任务字段
        for (String field : TASK_FIELDS) {
            if (map.containsKey(field)) task.put(field, map.get(field));
        }
        // 工匠字段
        for (String field : CRAFTSMAN_FIELDS) {
            if (map.containsKey(field)) craftsman.put(field.substring(10), map.get(field));
        }
        // 其他字段补充
        for (String key : map.keySet()) {
            if (!result.containsKey(key) && !task.containsKey(key) && !key.startsWith("craftsman_")) {
                result.put(key, map.get(key));
            }
        }
        result.put("task", task);
        result.put("craftsman", craftsman);
        return result;
    }

    @PostMapping
    public Result<?> add(@RequestBody TaskCollect taskCollect) {
        taskCollectService.save(taskCollect);
        return Result.success();
    }

    @DeleteMapping("/{taskId}/{craftsmanId}")
    public Result<?> delete(@PathVariable Long taskId, @PathVariable Long craftsmanId) {
        QueryWrapper<TaskCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", taskId).eq("craftsman_id", craftsmanId);
        taskCollectService.remove(wrapper);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody TaskCollect taskCollect) {
        QueryWrapper<TaskCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", taskCollect.getTaskId()).eq("craftsman_id", taskCollect.getCraftsmanId());
        taskCollectService.update(taskCollect, wrapper);
        return Result.success();
    }

    @GetMapping("/{taskId}/{craftsmanId}")
    public Result<Map<String, Object>> get(@PathVariable Long taskId, @PathVariable Long craftsmanId) {
        Map<String, Object> collect = taskCollectService.getCollectWithTaskByTaskAndCraftsman(taskId, craftsmanId);
        return Result.success(wrapTaskCollect(collect));
    }

    @GetMapping("/list")
    public Result<List<Map<String, Object>>> list() {
        List<Map<String, Object>> list = taskCollectService.getAllCollectWithTask();
        list.replaceAll(this::wrapTaskCollect);
        return Result.success(list);
    }

    /**
     * 根据工匠ID查询该工匠的所有收藏任务
     */
    @GetMapping("/craftsman/{craftsmanId}")
    public Result<List<Map<String, Object>>> getByCraftsmanId(@PathVariable Long craftsmanId) {
        List<Map<String, Object>> collects = taskCollectService.getCollectWithTaskByCraftsmanId(craftsmanId);
        collects.replaceAll(this::wrapTaskCollect);
        return Result.success(collects);
    }

    /**
     * 根据工匠ID查询该工匠的所有收藏任务（带任务详情）
     */
    @GetMapping("/withTask/craftsman/{craftsmanId}")
    public Result<List<Map<String, Object>>> getCollectWithTaskByCraftsmanId(@PathVariable Long craftsmanId) {
        List<Map<String, Object>> result = taskCollectService.getCollectWithTaskByCraftsmanId(craftsmanId);
        result.replaceAll(this::wrapTaskCollect);
        return Result.success(result);
    }
} 